package com.chris.oauth2.web.oauth2;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.chris.oauth2.service.AuthService;
import com.chris.oauth2.util.IdUtil;
import com.chris.oauth2.util.MD5Util;

@Controller
@RequestMapping("oauth2")
public class AuthorizeController {

	@Autowired
	AuthService authService;

	@RequestMapping("authorize")
	@Transactional
	public ModelAndView authorize(@RequestParam String appid, @RequestParam String secret,
			@RequestParam String response_type, @RequestParam(required = false) String state,
			@RequestParam(required = false) String redirect_uri) {
		ModelMap modelMap = new ModelMap();
		if (!authService.checkClientId(appid)) {
			modelMap.addAttribute("errcode", 201);
			modelMap.addAttribute("errmsg", "invalid appid");
			return new ModelAndView("jsonView", modelMap);
		}
		if (!authService.checkClientSecret(secret)) {
			modelMap.addAttribute("errcode", 202);
			modelMap.addAttribute("errmsg", "invalid secret");
			return new ModelAndView("jsonView", modelMap);
		}
		if (StringUtils.isBlank(response_type) || !"code".equals(response_type)) {
			modelMap.addAttribute("errcode", 206);
			modelMap.addAttribute("errmsg", "invalid response_type");
			return new ModelAndView("jsonView", modelMap);
		}

		String code = MD5Util.encode((IdUtil.generateId() + appid).getBytes());

		authService.addAuthCode(code, appid);
		if (StringUtils.isBlank(redirect_uri)) {
			modelMap.addAttribute("code", code);
			modelMap.addAttribute("state", state);
			return new ModelAndView("jsonView", modelMap);
		} else {
			ModelAndView r = new ModelAndView();
			r.setViewName("redirect:" + redirect_uri
					+ ((redirect_uri.contains("?") ? "&" : "?") + "code=" + code + "&state=" + state));
			return r;
		}
	}

}
